package org.example.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockEasy {
    private Lock lock =new ReentrantLock();   //可重入锁
    public void myMethod1(){
        try {
            lock.lock();
            System.out.println("myMethod1 invoked");
        }finally {
//            lock.unlock();
        }

    }
    public void myMethod2(){
        /*try {
            lock.lock();
            System.out.println("myMethod2 invoked");
        }finally {
            lock.unlock();
        }*/
        boolean result =false;
        try {
            //等待800ms后放弃获取锁，防止死锁
            result=lock.tryLock(800, TimeUnit.MILLISECONDS);
        }catch(InterruptedException e){
            e.printStackTrace();
        }

        if(result){
            System.out.println("get the lock");
        }else {
            System.out.println("can't get the lock");
        }

    }

    public static void main(String[]args){
        ReentrantLockEasy myTest1=new ReentrantLockEasy();
        Thread t1=new Thread(()->{
            for(int i=0;i<10;++i){
                myTest1.myMethod1();
                try {
                    Thread.sleep(2000);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        Thread t2=new Thread(()->{
            for(int i=0;i<10;++i){
                myTest1.myMethod2();
                try {
                    Thread.sleep(300);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }


}
